package cn.ywyself.extend.handle;

import cn.ywyself.extend.utils.RenderUtils;
import com.jfinal.handler.Handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 非法请求过滤，避免直接显示HTML模板内容<br>
 * 实现伪静态处理
 */
public class WebResourceHandler extends Handler {
    private static final List<String> SUFFIX_LIST = Arrays.asList(".htm", ".html", ".shtml", ".xhtml", ".jsp", ".asp", ".aspx", ".php");


    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        // 请求静态网页文件
        boolean forbidden = false;
        // 伪静态
        for (String suffix : SUFFIX_LIST) {
            if (target.contains(suffix)) {
                // 改成用点来判断，避免如.html3时绕过了处理
                target = target.substring(0, target.lastIndexOf("."));
                break;
            }
        }
        // 静态页面过滤
        for (String suffix : SUFFIX_LIST) {
            if (target.contains(suffix) && target.lastIndexOf(".") != -1) {
                forbidden = true;
                break;
            }
        }
        // js 源码过滤
        if (target.endsWith(".src.js")) {
            forbidden = true;
        }
        if (forbidden) {
            RenderUtils.renderError(request, response, isHandled, 404);
        } else {
            next.handle(target, request, response, isHandled);
        }
    }
}
